package edu.gyc.swing.test;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.Timer;

public class HiPic2 extends JFrame   {
    public static final int WIDTH = 800;
    public static final int HEIGHT = 600;
    private JFileChooser fileChooser = new JFileChooser();
    //存放目标目录里图片文件的真实路径
    private List<String> picFilePaths = new ArrayList<>();
    private String currentPicPath;
    private JButton previousBt,nextBt;
    private JButton openBt,carouselBt;
    //图片显示的载体，和状态栏
    private JLabel picLabel,statusLabel;
    private int count=0;
    private Timer timer;
    public static String filePath = "K:" + System.getProperty("file.separator") + "girls";//默认只能打开的跟路径

    public HiPic2()  {
        super("PhotoViewer");
        setSize(WIDTH,HEIGHT);
        JPanel panel = new JPanel();
         openBt = new JButton("Open");
        panel.add(openBt);
         carouselBt = new JButton("幻灯播放");
        panel.add(carouselBt);
        getContentPane().add(panel, BorderLayout.NORTH);
        fileChooser.setCurrentDirectory(new File(filePath));
        //文件名过滤器，让fileChooser只显示目录类指定类型的文件
        FileNameExtensionFilter fileNameExtensionFilter = new FileNameExtensionFilter("ImageFiles", "jpg"
                , "jpeg");
        fileChooser.setFileFilter(fileNameExtensionFilter);
        openBt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fileChooser.setCurrentDirectory(new File(filePath));
                int result = fileChooser.showOpenDialog(null);
                if (result == JFileChooser.APPROVE_OPTION) {
                    //用户选中了图片文件地址
                    currentPicPath=fileChooser.getSelectedFile().getAbsolutePath();
                    //获取选中图片的目录地址
                    String picDir=fileChooser.getSelectedFile().getParent();
                    //显示图片
                   scalePic(currentPicPath);
                   //开启一个线程搜索指定目录下所有图片地址放置在picFilePaths中
                   asyncGetPicPath(picDir);
                    picLabel.requestFocus();
                }

            }
        });

        carouselBt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        count++;
                        if (count >= picFilePaths.size()) {
                            count=0;
                        }
                        scalePic(picFilePaths.get(count));
                    }
                },0,3000);

                picLabel.requestFocus();
                carouselBt.setEnabled(false);
            }
        });

        picLabel = new JLabel();
        picLabel.addKeyListener(new HiKeyListener());
        getContentPane().add(picLabel, BorderLayout.CENTER);
        statusLabel = new JLabel("当前文件是：");
        getContentPane().add(statusLabel, BorderLayout.SOUTH);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);

    }

    private void showPic(String path) {
        ImageIcon icon=new ImageIcon(path);
        icon=new ImageIcon(icon.getImage());
        picLabel.setIcon(icon);
        picLabel.setHorizontalAlignment(SwingConstants.CENTER);
        statusLabel.setText("当前文件："+path+" widht:"+icon.getIconWidth()+" height:"+icon.getIconHeight());
    }

    private void scalePic(String path) {
        ImageIcon icon = new ImageIcon(path);
        //等比缩放条件
        int imgWidth = icon.getIconWidth();
        int imgHeight = icon.getIconHeight();
        System.out.println("imgWidth: " + imgWidth + " imgHeight:" + imgHeight);
        int targetWidth = picLabel.getWidth();
        int targetHeight = picLabel.getHeight();
        System.out.println("targetWidth: " + targetWidth + " targetHeight:" + targetHeight);
        int reImgWidth = 0;
        int reImgHeight = 0;
        float resize = 0;
        float resize1 = 0;
        float resize2 = 0;
        resize1 = (float) (targetHeight * 1.0 / imgHeight);
        resize2 = (float) (targetWidth * 1.0 / imgWidth);
        if (resize1 > resize2) {
            resize = resize2;
        } else {
            resize = resize1;
        }
        System.out.println("resize: " + resize);
        if (resize >= 1) { //小图片就原样输出
            reImgWidth = imgWidth;
            reImgHeight = imgHeight;
        } else {
            reImgWidth = (int) (imgWidth * resize);
            reImgHeight = (int) (imgHeight * resize);
        }
        System.out.println("reImgWidth " + reImgWidth + " reImgHeight" + reImgHeight);
        //这个是按等比缩放
        icon = new ImageIcon(icon.getImage().getScaledInstance(reImgWidth, reImgHeight, Image.SCALE_SMOOTH));
        picLabel.setIcon(icon);
        picLabel.setHorizontalAlignment(SwingConstants.CENTER);
        String s = "当前文件：" + path + " widht:" + imgWidth + " height:" + imgHeight;

    }

    class HiKeyListener implements KeyListener {

        @Override
        public void keyTyped(KeyEvent e) {

        }

        @Override
        public void keyPressed(KeyEvent e) {
            System.out.println("key pressed "+e);
            if (timer != null) {
                timer.cancel();
            }
            carouselBt.setEnabled(true);
            switch (e.getKeyCode()) {
                case KeyEvent.VK_LEFT:
                    count--;
                    if (count<0) {
                        count=picFilePaths.size()-1;
                    }
                    scalePic(picFilePaths.get(count));
                    break;
                case KeyEvent.VK_RIGHT:
                    count++;
                    if (count >= picFilePaths.size()) {
                        count=0;
                    }
                    scalePic(picFilePaths.get(count));
                    break;
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {

        }
    }

    public void getDirPicPath(String dir) {
        File file = new File(dir);
        if (!file.exists()) {
            JOptionPane.showMessageDialog(null,dir+" 路径不存在！");
        }
        String[]  fileNames=file.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if (name.endsWith("jpg") || name.endsWith("jpeg") ) {
                    return true;
                }
                return false;
            }
        });

        picFilePaths.addAll(Arrays.asList(fileNames));
        System.out.println(picFilePaths);
      //  Collections.sort(picFilePaths);//字符串排序
        //按数字大小排序
        Collections.sort(picFilePaths, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                int i = extractNumber(o1);
                int j = extractNumber(o2);

                return i-j;
            }
        });
        System.out.println(picFilePaths);
        for (int i = 0; i < picFilePaths.size(); i++) {
            String s = picFilePaths.get(i);
            s=dir+File.separator+s;
            picFilePaths.set(i, s);
        }
        System.out.println(picFilePaths);


    }
    private static int extractNumber(String name) {
        int i;
        try {
            String number = name.replaceAll("[^\\d]", "");
            i = Integer.parseInt(number);
        } catch (Exception e) {
            i = 0;
        }
        return i;
    }
    private void asyncGetPicPath(String path) {
        picFilePaths.clear();
        new Thread(new Runnable() {
            @Override
            public void run() {
                getDirPicPath(path);
                JOptionPane.showMessageDialog(null,path+"目录文件检索完毕，共有图片"+picFilePaths.size());
                if (picFilePaths.size() > 0) {
                    String path = picFilePaths.get(0);
                }
            }
        }).start();
    }

   public static void main(String[] args) {
       HiPic2 hiPic=new HiPic2();
   }



}

